<template>
  <div class="app-container">
    <div class="filter-container" style="display: flex;align-items: center;justify-content: space-between;">
      <el-button @click="handleDownload" :loading="downloadLoading" v-waves size="mini" type="success">
        导出选中
      </el-button>
      <div>
        <el-input v-model="listQuery.title" size="mini" placeholder="用户名" style="width: 200px;" class="filter-item"
          @keyup.enter.native="handleFilter" />
        <el-button v-waves size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          搜索
        </el-button>
      </div>
    </div>

    <el-table ref="multipleTable" :key="tableKey" v-loading="listLoading" :data="list" border fit highlight-current-row
      style="width: 100%;" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="订单号" width="100" prop="no" />
      <el-table-column label="商品名称" align="center" width="150">
        <template slot-scope="{row}">
          <p v-for="(item,index) in row.goods" :key="index">{{item.title }}</p>
        </template>
      </el-table-column>
      <el-table-column label="订单类型" align="center">
        <template slot-scope="{row}">
          <span>{{ row.type | typeFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付状态" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.status==='success'?'success':'danger'" size="mini">{{ row.status | statusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="原价/实付（元）" align="center">
        <template slot-scope="{row}">
          <span style="color: #888888;">{{ row.price }}</span>
          <span style="color: #888888;">/</span>
          <span style="color:red;">{{ row.total_price }}</span>
        </template>
      </el-table-column>
      <el-table-column label="支付方式" align="center">
        <template slot-scope="{row}">
          <el-tag type="info" size="mini">{{ row.pay_method | methodFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建/支付时间" width="150" align="center">
        <template slot-scope="{row}">
          <span>{{ row.pay_time}}/{{row.created_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">

          <el-popconfirm style="margin-left: 10px;" title="是否要删除该记录" @onConfirm="handleDelete(row,$index)">
            <el-button slot="reference" type="danger" size="mini" @click="">
              删除
            </el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
      @pagination="getList" />
  </div>
</template>

<script>
  import waves from '@/directive/waves' // waves directive
  import {
    fetchList,
    deleteOrder
  } from '@/api/order'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  let typeOptions = {
    group: '团购',
    default: '普通订单'
  }
  let statusOptions = {
    pendding: '支付中',
    fail: '支付失败',
    success: '支付成功'
  }
  let payOptions = {
    wechat: '微信支付'
  }
  export default {
    components: {
      Pagination
    },
    directives: {
      waves
    },
    data() {
      return {
        tableKey: 0,
        list: null,
        total: 0,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          status: undefined,
          title: undefined
        },
        multipleSelection: [],
        downloadLoading: false,
        filename: '',
        autoWidth: true,
        bookType: 'xlsx'
      }
    },
    filters: {
      typeFilter(value) {
        return typeOptions[value];
      },
      statusFilter(value) {
        return statusOptions[value];
      },
      methodFilter(value) {
        return payOptions[value];
      }
    },
    created() {
      this.getList()
    },
    methods: {
      handleDelete(row, index) {
        deleteOrder().then(res => {
          this.$notify({
            title: '成功提示',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.list.splice(index, 1)
        })
      },
      getList() {
        this.listLoading = true
        console.log(this.listQuery)
        fetchList(this.listQuery).then(response => {
          this.list = response.data.items
          this.total = response.data.total
          // Just to simulate the time of the request
          setTimeout(() => {
            this.listLoading = false
          }, 1.5 * 1000)
        })
      },
      handleFilter() {
        this.listQuery.page = 1
        this.listQuery.status = parseInt(this.listQuery.status)
        this.getList()
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleDownload() {
        if (this.multipleSelection.length === 0) {
          return this.$message.error('清先选择需要导出的数据')
        }
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const filterVal = ['no', 'goods', 'type', 'status', 'price', 'total_price', 'pay_method', 'created_time']
          const tHeader = ['订单号', '商品名称', '订单类型', '订单状态', '原价(元)', '总价(元)', '支付方式', '支付时间']
          const list = this.multipleSelection.map(item => {
            let o = { ...item }
            o.type = typeOptions[item.type]
            o.goods = item.goods.map(item => item.title).join(',')
            o.pay_method = payOptions[item.pay_method]
            o.status = statusOptions[item.status]
            return o
          })
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }

</script>